package com.lh.handler;

import com.lh.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 全局Controller类返回结果处理配置类
 *
 * @Author LuoHang
 * @Date 2022-05-10 17:15
 **/
@ControllerAdvice(annotations = {Controller.class, RestController.class})
public class GlobalResponseHandler implements ResponseBodyAdvice<Object> {
    public static final Logger logger = LoggerFactory.getLogger(GlobalResponseHandler.class);

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    /**
     * 结果返回页面之前对数据进行处理
     * @param body 结果
     * @param returnType 返回类型
     * @param selectedContentType 参数类型
     * @param selectedConverterType 解析类型
     * @param request 请求对象
     * @param response 相应对象
     * @return 返回
     */
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        logger.info("GlobalResponseHandler.beforeBodyWrite()方法开始执行.........");
        if (body instanceof User){
            User user = (User) body;
            if (user.getId() == null){
                user.setId(-1);
                user.setUsername("GlobalResponseHandler");
                user.setPassword("beforeBodyWrite");
            }
        }
        return body;
    }
}
